# 评价两个气泡重叠时，重叠面积检测的准确性
import os.path
import cv2
import glob
from matplotlib import pyplot as plt
from ellipsefit_ltl import ellipse_detect, ellipse_detect_hronly
import xlsxwriter


path='D:\\whitebubble\\machinelearning\\preprocessing\\gen_overlop_ideal0901\\'
excel_path='excel-overlop_ideal0901.xlsx'
img_paths = glob.glob(os.path.join(path,'*.jpg'))

#对目录下的文件进行遍历
j=0
ground = []
predict = []
error = []
overlop_ratio = []
num=[]
for file in img_paths:
#判断是否是文件
    if os.path.isfile(file)==True:
#设置新文件名
        crop = cv2.imread(file)
        print(file)
        crop = cv2.bitwise_not(crop) # 二值化反转
        [height, weidth, deep]= crop.shape
        if weidth < 15 or height < 15:  # 动态的上采样倍数吧
            times = 3
        elif weidth < 30 or height < 30:
            times = 2
        else:
            times = 2
        _ellopse, area = ellipse_detect_hronly(crop, times)

        # 读取同名txt的真实面积数据
        imgname = (os.path.splitext(os.path.basename(file)))[0] # 将检测过程以及结果图片，保存在相同名称的文件夹内
        txt_path = path+imgname+'.txt'
        print(txt_path)
        txt = open(txt_path, 'r')
        txt_context = txt.readlines()
        # real_area = int(txt_context[0])
        real_area = float(txt_context[0])
        overlop_ratio.append(float(txt_context[1]))
        ground.append(real_area)
        predict.append(area)
        error.append(abs(area-real_area)/real_area)
        print(abs(area-real_area)/real_area)
        num.append(int(imgname))
        j+=1

workbook = xlsxwriter.Workbook(excel_path)
worksheet = workbook.add_worksheet()
worksheet.write_column('A1',num)
worksheet.write_column('B1',ground)
worksheet.write_column('C1',predict)
worksheet.write_column('D1',error)
worksheet.write_column('E1',overlop_ratio)

workbook.close()

#plt.scatter(list(range(len(error))), error) # 误差值比例
plt.scatter(overlop_ratio, error) # 误差值与重叠比例的关系
plt.show()

#结束
print ("End")